<!DOCTYPE html>
<html lang="zh-Hans">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<meta name="theme-color" content="#222"><meta name="generator" content="Hexo 6.2.0">


  <link rel="apple-touch-icon" sizes="180x180" href="/vhuichen.ico">
  <link rel="icon" type="image/png" sizes="32x32" href="/vhuichen.ico">
  <link rel="icon" type="image/png" sizes="16x16" href="/vhuichen.ico">
  <link rel="mask-icon" href="/vhuichen.ico" color="#222">

<link rel="stylesheet" href="/css/main.css">



<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.0/css/all.min.css" integrity="sha256-AbA177XfpSnFEvgpYu1jMygiLabzPCJCRIBtR5jGc0k=" crossorigin="anonymous">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.1.1/animate.min.css" integrity="sha256-PR7ttpcvz8qrF57fur/yAx1qXMFJeJFiA6pSzWi0OIE=" crossorigin="anonymous">

<script class="next-config" data-name="main" type="application/json">{"hostname":"vhuichen.github.io","root":"/","images":"/images","scheme":"Pisces","darkmode":false,"version":"8.13.0","exturl":false,"sidebar":{"position":"left","display":"display","padding":18,"offset":12},"copycode":{"enable":false,"style":null},"bookmark":{"enable":false,"color":"#222","save":"auto"},"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"stickytabs":false,"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"fadeInDown","post_body":"fadeInDown","coll_header":"fadeInLeft","sidebar":"fadeInUp"}},"prism":false,"i18n":{"placeholder":"Searching...","empty":"We didn't find any results for the search: ${query}","hits_time":"${hits} results found in ${time} ms","hits":"${hits} results found"}}</script><script src="/js/config.js"></script>

    <meta name="description" content="两种方法1、machO文件中 通过 __objc_classlist  __objc_classrefs 对比2、运行时获取到未使用的类（需要大量测试，或者线上测试）两种方法都不能绝对识别准确，但合并起来准确率很高了，最终再手动确定    12345678910111213141516171819202122232425262728293031323334353637383940414243444">
<meta property="og:type" content="article">
<meta property="og:title" content="iOS检测未使用的类">
<meta property="og:url" content="https://vhuichen.github.io/2021/04/iOS/iOS%E6%A3%80%E6%B5%8B%E6%9C%AA%E4%BD%BF%E7%94%A8%E7%9A%84%E7%B1%BB/index.html">
<meta property="og:site_name" content="vhuichen">
<meta property="og:description" content="两种方法1、machO文件中 通过 __objc_classlist  __objc_classrefs 对比2、运行时获取到未使用的类（需要大量测试，或者线上测试）两种方法都不能绝对识别准确，但合并起来准确率很高了，最终再手动确定    12345678910111213141516171819202122232425262728293031323334353637383940414243444">
<meta property="og:locale">
<meta property="article:published_time" content="2021-04-12T16:00:00.000Z">
<meta property="article:modified_time" content="2021-04-26T15:51:56.594Z">
<meta property="article:author" content="vhuichen">
<meta property="article:tag" content="体积包优化">
<meta name="twitter:card" content="summary">


<link rel="canonical" href="https://vhuichen.github.io/2021/04/iOS/iOS%E6%A3%80%E6%B5%8B%E6%9C%AA%E4%BD%BF%E7%94%A8%E7%9A%84%E7%B1%BB/">



<script class="next-config" data-name="page" type="application/json">{"sidebar":"","isHome":false,"isPost":true,"lang":"zh-Hans","comments":true,"permalink":"https://vhuichen.github.io/2021/04/iOS/iOS%E6%A3%80%E6%B5%8B%E6%9C%AA%E4%BD%BF%E7%94%A8%E7%9A%84%E7%B1%BB/","path":"2021/04/iOS/iOS检测未使用的类/","title":"iOS检测未使用的类"}</script>

<script class="next-config" data-name="calendar" type="application/json">""</script>
<title>iOS检测未使用的类 | vhuichen</title>
  






  <noscript>
    <link rel="stylesheet" href="/css/noscript.css">
  </noscript>
</head>

<body itemscope itemtype="http://schema.org/WebPage" class="use-motion">
  <div class="headband"></div>

  <main class="main">
    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="Toggle navigation bar" role="button">
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <i class="logo-line"></i>
      <p class="site-title">vhuichen</p>
      <i class="logo-line"></i>
    </a>
      <p class="site-subtitle" itemprop="description">记录、分享</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
    </div>
  </div>
</div>



<nav class="site-nav">
  <ul class="main-menu menu"><li class="menu-item menu-item-home"><a href="/" rel="section">Home</a></li><li class="menu-item menu-item-archives"><a href="/archives/" rel="section">Archives</a></li><li class="menu-item menu-item-about"><a href="/about/" rel="section">About</a></li>
  </ul>
</nav>




</div>
        
  
  <div class="toggle sidebar-toggle" role="button">
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
  </div>

  <aside class="sidebar">

    <div class="sidebar-inner sidebar-nav-active sidebar-toc-active">
      <ul class="sidebar-nav">
        <li class="sidebar-nav-toc">
          Table of Contents
        </li>
        <li class="sidebar-nav-overview">
          Overview
        </li>
      </ul>

      <div class="sidebar-panel-container">
        <!--noindex-->
        <div class="post-toc-wrap sidebar-panel">
            <div class="post-toc animated"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#%E7%BC%BA%E7%82%B9"><span class="nav-number">1.</span> <span class="nav-text">缺点</span></a></li></ol></div>
        </div>
        <!--/noindex-->

        <div class="site-overview-wrap sidebar-panel">
          <div class="site-author site-overview-item animated" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="vhuichen"
      src="/images/vhuichen.jpg">
  <p class="site-author-name" itemprop="name">vhuichen</p>
  <div class="site-description" itemprop="description"></div>
</div>
<div class="site-state-wrap site-overview-item animated">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
        <a href="/archives/">
          <span class="site-state-item-count">78</span>
          <span class="site-state-item-name">posts</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
          <a href="/categories/">
        <span class="site-state-item-count">11</span>
        <span class="site-state-item-name">categories</span></a>
      </div>
      <div class="site-state-item site-state-tags">
          <a href="/tags/">
        <span class="site-state-item-count">86</span>
        <span class="site-state-item-name">tags</span></a>
      </div>
  </nav>
</div>



        </div>
      </div>
    </div>
  </aside>
  <div class="sidebar-dimmer"></div>


    </header>

    
  <div class="back-to-top" role="button" aria-label="Back to top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>

<noscript>
  <div class="noscript-warning">Theme NexT works best with JavaScript enabled</div>
</noscript>


    <div class="main-inner post posts-expand">


  


<div class="post-block">
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-content" lang="zh-Hans">
    <link itemprop="mainEntityOfPage" href="https://vhuichen.github.io/2021/04/iOS/iOS%E6%A3%80%E6%B5%8B%E6%9C%AA%E4%BD%BF%E7%94%A8%E7%9A%84%E7%B1%BB/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/vhuichen.jpg">
      <meta itemprop="name" content="vhuichen">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="vhuichen">
      <meta itemprop="description" content="">
    </span>

    <span hidden itemprop="post" itemscope itemtype="http://schema.org/CreativeWork">
      <meta itemprop="name" content="iOS检测未使用的类 | vhuichen">
      <meta itemprop="description" content="">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          iOS检测未使用的类
        </h1>

        <div class="post-meta-container">
          <div class="post-meta">
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar"></i>
      </span>
      <span class="post-meta-item-text">Posted on</span>

      <time title="Created: 2021-04-13 00:00:00" itemprop="dateCreated datePublished" datetime="2021-04-13T00:00:00+08:00">2021-04-13</time>
    </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar-check"></i>
      </span>
      <span class="post-meta-item-text">Edited on</span>
      <time title="Modified: 2021-04-26 23:51:56" itemprop="dateModified" datetime="2021-04-26T23:51:56+08:00">2021-04-26</time>
    </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-folder"></i>
      </span>
      <span class="post-meta-item-text">In</span>
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/categories/iOS/" itemprop="url" rel="index"><span itemprop="name">iOS</span></a>
        </span>
    </span>

  
</div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">
        <p>两种方法<br>1、machO文件中 通过 <code>__objc_classlist</code>  <code>__objc_classrefs</code> 对比<br>2、运行时获取到未使用的类（需要大量测试，或者线上测试）<br>两种方法都不能绝对识别准确，但合并起来准确率很高了，最终再手动确定   </p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br></pre></td><td class="code"><pre><span class="line">#include &lt;dlfcn.h&gt;</span><br><span class="line">#include &lt;mach-o/dyld.h&gt;</span><br><span class="line">#include &lt;mach-o/getsect.h&gt;</span><br><span class="line"></span><br><span class="line">/* 获取 runtime 未使用的类 */</span><br><span class="line">NSMutableSet&lt;NSString *&gt; *runtimeUnusedClass() &#123;</span><br><span class="line">    Dl_info info;</span><br><span class="line">    dladdr((const void *)&amp;runtimeUnusedClass, &amp;info);</span><br><span class="line">    </span><br><span class="line">    const uint64_t mach_header = (uint64_t)info.dli_fbase;</span><br><span class="line">    </span><br><span class="line">    const struct section_64 *classlist = getsectbynamefromheader_64((const struct mach_header_64 *)mach_header, &quot;__DATA&quot;, &quot;__objc_classlist&quot;);</span><br><span class="line">    </span><br><span class="line">    if (classlist) &#123;</span><br><span class="line">        NSMutableSet *classlistUnused = [[NSMutableSet alloc] init];</span><br><span class="line">        // 遍历拿到所有的类</span><br><span class="line">        for (UInt64 addr = classlist-&gt;offset; addr &lt; classlist-&gt;offset + classlist-&gt;size; addr += sizeof(const char **)) &#123;</span><br><span class="line">            uint64_t baseArrr = mach_header + addr;</span><br><span class="line">            </span><br><span class="line">            //获取类对象指针</span><br><span class="line">            uint64_t object_class_addr = *(uint64_t *)(baseArrr);</span><br><span class="line">            //</span><br><span class="line">            uint64_t object_class_isa = *(uint64_t *)(object_class_addr);</span><br><span class="line">            //获取元类对象</span><br><span class="line">            uint64_t object_meta_class_addr;</span><br><span class="line">            if (object_class_isa &amp; (1 &lt;&lt; 0)) &#123;</span><br><span class="line">                object_meta_class_addr = object_class_addr;</span><br><span class="line">            &#125; else &#123;</span><br><span class="line">                object_meta_class_addr = object_class_isa &amp; 0x00007ffffffffff8ULL;</span><br><span class="line">            &#125;</span><br><span class="line">            //偏移32个字节，拿到 class_data_bits 的地址</span><br><span class="line">            uint64_t class_data_bits_addr = object_meta_class_addr + 32;</span><br><span class="line">            //取 class_data_bits 的值</span><br><span class="line">            uint64_t class_data_bits = *(uint64_t *)(class_data_bits_addr);</span><br><span class="line">            //得到 class_rw_t 的指针 (class_rw_t *)(bits &amp; FAST_DATA_MASK);</span><br><span class="line">            uint64_t class_rw_addr = (class_data_bits &amp; 0x00007ffffffffff8UL);</span><br><span class="line">            //取指针的值，得到的第一个数据就是 flags</span><br><span class="line">            uint64_t flags = *(uint64_t *)(class_rw_addr);</span><br><span class="line">            //</span><br><span class="line">            bool isInitialized = flags &amp; (1 &lt;&lt; 29);</span><br><span class="line">            </span><br><span class="line">            if (!isInitialized) &#123;</span><br><span class="line">                //打印类会导致类初始化，所以此方法只能使用一次</span><br><span class="line">                NSString *class = [NSString stringWithFormat:@&quot;%@&quot;, (void *)object_class_addr];</span><br><span class="line">                [classlistUnused addObject:class];</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        return classlistUnused;</span><br><span class="line">    &#125;</span><br><span class="line">    return nil;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">/* 获取 MachO 未使用的类 */</span><br><span class="line">NSMutableSet&lt;NSString *&gt; *machOUnusedClass() &#123;</span><br><span class="line">    Dl_info info;</span><br><span class="line">    dladdr((const void *)&amp;machOUnusedClass, &amp;info);</span><br><span class="line">    </span><br><span class="line">    const uint64_t mach_header = (uint64_t)info.dli_fbase;</span><br><span class="line">    </span><br><span class="line">    const struct section_64 *classlist = getsectbynamefromheader_64((const struct mach_header_64 *)mach_header, &quot;__DATA&quot;, &quot;__objc_classlist&quot;);</span><br><span class="line">    const struct section_64 *selfrefs = getsectbynamefromheader_64((const struct mach_header_64 *)mach_header, &quot;__DATA&quot;, &quot;__objc_classrefs&quot;);</span><br><span class="line">    </span><br><span class="line">    if (classlist &amp;&amp; selfrefs) &#123;</span><br><span class="line">        NSMutableSet *classlistSet = [[NSMutableSet alloc] init];</span><br><span class="line">        for (UInt64 addr = classlist-&gt;offset; addr &lt; classlist-&gt;offset + classlist-&gt;size; addr += sizeof(const char **)) &#123;</span><br><span class="line">            uint64_t baseArrr = mach_header + addr;</span><br><span class="line">            Class cls = (__bridge Class)(*(void **)(baseArrr));</span><br><span class="line">            NSString *clsString = [NSString stringWithFormat:@&quot;%@&quot;,cls];</span><br><span class="line">            [classlistSet addObject:clsString];</span><br><span class="line">        &#125;</span><br><span class="line">        </span><br><span class="line">        NSMutableSet *selfrefsSet = [[NSMutableSet alloc] init];</span><br><span class="line">        for (UInt64 addr = selfrefs-&gt;offset; addr &lt; selfrefs-&gt;offset + selfrefs-&gt;size; addr += sizeof(const char **)) &#123;</span><br><span class="line">            uint64_t baseArrr = mach_header + addr;</span><br><span class="line">            </span><br><span class="line">            Class cls = (__bridge Class)(*(void **)(baseArrr));</span><br><span class="line">            while (cls) &#123;</span><br><span class="line">                [selfrefsSet addObject:[NSString stringWithFormat:@&quot;%@&quot;,cls]];</span><br><span class="line">                cls = [cls superclass];</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        [classlistSet minusSet:selfrefsSet];</span><br><span class="line">        </span><br><span class="line">        return  classlistSet;</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    return nil;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<h2 id="缺点"><a href="#缺点" class="headerlink" title="缺点"></a>缺点</h2><p>1、<code>runtimeUnusedClass</code> 方法只有在第一次调用有效，而且必须手动浏览所有的页面（可以考虑放到线上收集）<br>2、两种方法都是不准确的，但未使用的类一定在其中，最终需要手动再次确认。</p>

    </div>

    
    
    

    <footer class="post-footer">
          <div class="post-tags">
              <a href="/tags/%E4%BD%93%E7%A7%AF%E5%8C%85%E4%BC%98%E5%8C%96/" rel="tag"># 体积包优化</a>
          </div>

        

          <div class="post-nav">
            <div class="post-nav-item">
                <a href="/2021/03/OperatingSystem/%E7%BA%BF%E7%A8%8B&%E8%BF%9B%E7%A8%8B/" rel="prev" title="线程&进程">
                  <i class="fa fa-chevron-left"></i> 线程&进程
                </a>
            </div>
            <div class="post-nav-item">
                <a href="/2021/04/NetworkProtocol/TCP%E5%8D%8F%E8%AE%AE/" rel="next" title="TCP协议">
                  TCP协议 <i class="fa fa-chevron-right"></i>
                </a>
            </div>
          </div>
    </footer>
  </article>
</div>






</div>
  </main>

  <footer class="footer">
    <div class="footer-inner">


<div class="copyright">
  &copy; 2015 – 
  <span itemprop="copyrightYear">2022</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">vhuichen</span>
</div>
  <div class="powered-by">Powered by <a href="https://hexo.io/" rel="noopener" target="_blank">Hexo</a> & <a href="https://theme-next.js.org/pisces/" rel="noopener" target="_blank">NexT.Pisces</a>
  </div>

    </div>
  </footer>

  
  <script src="https://cdnjs.cloudflare.com/ajax/libs/animejs/3.2.1/anime.min.js" integrity="sha256-XL2inqUJaslATFnHdJOi9GfQ60on8Wx1C2H8DYiN1xY=" crossorigin="anonymous"></script>
<script src="/js/comments.js"></script><script src="/js/utils.js"></script><script src="/js/motion.js"></script><script src="/js/next-boot.js"></script>

  





  





</body>
</html>
